package Chapter4;

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;

import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Parameterized;
import org.openqa.selenium.WebDriver;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@RunWith(value = Parameterized.class)
public class SimpleDDT {

    private static WebDriver driver;
    private static StringBuffer verificationErrors = new StringBuffer();

    private String height;
    private String weight;
    private String bmi;
    private String bmiCategory;

    @Parameters
    public static Collection testData(){
        return Arrays.asList(
                new Object[][] {
                        {"160","45","17.6","Underweight"},
                        {"168","70","24.8","Normal"},
                        {"181","89","27.2","Overweight"},
                        {"178","100","31.6","Obesity"}
                }
        );
    }

    public SimpleDDT(String height, String weight, String bmi, String bmiCategory)
    {
        this.height = height;
        this.weight = weight;
        this.bmi = bmi;
        this.bmiCategory = bmiCategory;
    }

    @BeforeClass
    public static void setUp() throws Exception
    {
        //Create new instance of the FireFox Driver
        driver = new FirefoxDriver();
        driver.get("http://dl.dropbox.com/u/55228056/bmicalculator.html");
        driver.manage().window().maximize();

    }

    @Test
    public void testBMICalculator() throws Exception
    {
        WebElement heightField = driver.findElement(By.name("heightCMS"));
        heightField.clear();
        heightField.sendKeys(this.height);

        WebElement weightField = driver.findElement(By.name("weightKg"));
        weightField.clear();
        weightField.sendKeys(this.weight);

        WebElement calculateButton = driver.findElement(By.id("Calculate"));
        calculateButton.click();

        try {
            WebElement bmiLabel = driver.findElement(By.name("bmi"));
            assertEquals(bmi, bmiLabel.getAttribute("value"));

            WebElement bmiCategoryLabel = driver.findElement(By.name("bmi_category"));
            assertEquals(bmiCategory, bmiCategoryLabel.getAttribute("value"));
        } catch (Error e) {
            verificationErrors.append(toString());
            System.err.println("Assertion Fail" + verificationErrors.toString());
        }
    }

    @AfterClass
    public static void tearDown() throws Exception
    {

        driver.quit();

        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)){
            fail(verificationErrorString);
        }
    }
}
